package com.ruoyi.common.security.utils;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.security.constant.SessionConstant;
import com.ruoyi.common.security.model.UserSession;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.util.Assert;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author resthx
 * @date 15:04 2022/5/28
 * satoken相关工具方法封装
 */
public class SaTokenUtils {
    /**
     * 登录用户，通过客户端
     * @param userInfo
     * @param type
     * @return
     */
    public static String loginByClient(LoginUser userInfo, String type) {
        Assert.notNull(userInfo.getSysUser(),"用户id为空");
        dealLoginUser(userInfo);
        //登录
        StpUtil.login(userInfo.getUserid(),type);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String tokenValue = tokenInfo.getTokenValue();
        long tokenTimeout = tokenInfo.getTokenTimeout();
        userInfo.setToken(tokenValue);
        userInfo.setExpireTime(tokenTimeout);
        userInfo.setSysUser(null);
        userInfo.setClient(type);
        //设置用户信息会话
        setUserSession(userInfo);
        //设置token信息会话
        setTokenSession(userInfo);
        //返回token
        return tokenValue;
    }

    private static void setTokenSession(LoginUser userInfo) {
        //权限缓存放入usersession，tokensession不用放,后期如果集成oauth2的话这里需要修改
        userInfo.setRoles(null);
        userInfo.setPermissions(null);
        userInfo.setRoleSet(null);
        StpUtil.getTokenSession().set(SessionConstant.TOKEN_SESSION_KEY,userInfo);
    }

    private static void dealLoginUser(LoginUser userInfo) {
        SysUser sysUser = userInfo.getSysUser();
        userInfo.setUserid(sysUser.getUserId());
        userInfo.setUsername(sysUser.getUserName());
        userInfo.setLoginTime(System.currentTimeMillis());
        userInfo.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        List<SysRole> roles = sysUser.getRoles();
        Set<SysRole> roleSet = new HashSet<SysRole>(roles);
        userInfo.setRoleSet(roleSet);
    }

    private static void setUserSession(LoginUser loginUser) {
        UserSession userSession = new UserSession();
        userSession.setRoles(loginUser.getRoles());
        userSession.setPermissions(loginUser.getPermissions());
        userSession.setUsername(loginUser.getUsername());
        userSession.setUserid(loginUser.getUserid());
        userSession.setRoleSet(loginUser.getRoleSet());
        StpUtil.getSession().set(SessionConstant.USER_SESSION_KEY,userSession);
    }

    public static SaSession getSaUserSession(){
        return StpUtil.getSession();
    }
}
